package top.auntie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.auntie.bean.OrgTypeSaveDto;
import top.auntie.bean.PageReq;
import top.auntie.dao.OrgTypeDao;
import top.auntie.dao.TypeDao;
import top.auntie.model.OrgType;
import top.auntie.model.OrgTypeExample;
import top.auntie.model.Type;
import top.auntie.model.TypeExample;
import top.auntie.service.OrgTypeService;
import top.auntie.util.DateTimeUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrgTypeServiceImpl implements OrgTypeService {

    @Autowired
    private OrgTypeDao orgTypeDao;

    @Autowired
    private TypeDao typeDao;

    @Override
    public PageInfo<?> query(PageReq pageReq) {
        PageHelper.startPage(pageReq.getPage(), pageReq.getLimit(), true);
        return new PageInfo<>(orgTypeDao.selectByExample(new OrgTypeExample()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(OrgTypeSaveDto orgTypeSaveDto) {
        OrgTypeExample example = new OrgTypeExample();
        example.createCriteria().andOrgIdEqualTo(orgTypeSaveDto.getOrgId());
        orgTypeDao.deleteByExample(example);
        final String now = DateTimeUtils.getNowDateTimeStr();
        List<OrgType> orgTypes = orgTypeSaveDto.getTypeIds().parallelStream().map(typeId-> new OrgType(orgTypeSaveDto.getOrgId(), typeId, now)).collect(Collectors.toList());
        orgTypes.forEach(orgType -> log.info(orgType.toString()));
        orgTypeDao.insertSelectiveBatch(orgTypes);
    }

    @Override
    public void delete() {

    }

    @Override
    public OrgType getOrgType() {
        return null;
    }

    @Override
    public List<Type> findTypeByOrgId(Integer orgId) {
        OrgTypeExample example = new OrgTypeExample();
        example.createCriteria().andOrgIdEqualTo(orgId);
        List<Integer> typeIds = orgTypeDao.selectByExample(example).parallelStream().map(OrgType::getTypeId).collect(Collectors.toList());
        if (typeIds.isEmpty()) {
            return new ArrayList<>();
        }
        TypeExample typeExample = new TypeExample();
        typeExample.createCriteria().andIdIn(typeIds);
        return typeDao.selectByExample(typeExample);
    }
}
